using MediatR;
using Microsoft.EntityFrameworkCore;
using Medical.Domain;
using Medical.ErrorCode;
using Medical.Infrastructrue.Interfaces;
using Medical.ReadApi.Appcontext.Command;
using Medical.ReadApi.Dto;

namespace Medical.ReadApi.Appcontext.CommandHandler
{
	public class GetInpatientOrderTemplatesListQueryHandler : IRequestHandler<GetInpatientOrderTemplatesListQuery, ApiPaging<InpatientOrderTemplateDto>>
	{
		private readonly IBaseRepository<InpatientOrderTemplate> _repository;

		public GetInpatientOrderTemplatesListQueryHandler(IBaseRepository<InpatientOrderTemplate> repository)
		{
			_repository = repository;
		}

		public async Task<ApiPaging<InpatientOrderTemplateDto>> Handle(GetInpatientOrderTemplatesListQuery request, CancellationToken cancellationToken)
		{
			var query = _repository.GetAll().Where(x => !x.IsDeleted);
			if (request.IsActive.HasValue) query = query.Where(x => x.IsActive == request.IsActive.Value);
			if (!string.IsNullOrEmpty(request.TemplateNameKeyword)) query = query.Where(x => x.TemplateName.Contains(request.TemplateNameKeyword));

			var totalCount = await query.CountAsync(cancellationToken);
			var items = await query
				.OrderByDescending(x => x.CreatedAt)
				.Skip((request.Page - 1) * request.Size)
				.Take(request.Size)
				.Select(x => new InpatientOrderTemplateDto
				{
					TemplateId = x.TemplateId,
					TemplateName = x.TemplateName,
					Description = x.Description,
					IsActive = x.IsActive,
					IsDefault = x.IsDefault,
					ShowSerialNumber = x.ShowSerialNumber,
					ShowDepartment = x.ShowDepartment,
					ShowDoctor = x.ShowDoctor,
					ShowPrescription = x.ShowPrescription,
					ShowBedNumber = x.ShowBedNumber,
					ShowConsultationTime = x.ShowConsultationTime,
					ShowAdmissionTime = x.ShowAdmissionTime,
					ShowDischargeTime = x.ShowDischargeTime,
					ShowExpenseDetails = x.ShowExpenseDetails,
					ShowCashier = x.ShowCashier,
					ShowAmount = x.ShowAmount,
					CreatedAt = x.CreatedAt,
					UpdatedAt = x.UpdatedAt
				})
				.ToListAsync(cancellationToken);

			var totalPage = (int)Math.Ceiling(totalCount / (double)request.Size);
			return new ApiPaging<InpatientOrderTemplateDto> { totalCount = totalCount, totalPage = totalPage, data = items };
		}
	}
}
